//
//  JKSectionStoryListViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/14.
//  Copyright © 2018年 安永博. All rights reserved.
//  某一专栏的文章列表

import UIKit

class JKSectionStoryListViewController: JKBaseViewController {
    
    /** 栏目模型 */
    public var section: JKNewsDetailSectionModel?
    
    
    // MARK: - 私有属性
    
    /** 模型数组 */
    private lazy var stories: [JKNewsListModel] = [JKNewsListModel]()
    
    /** 加载更多的时间戳数组 */
    private lazy var timestamps: [NSNumber] = [NSNumber]()
    
    // MARK:- 生命周期方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func setupNav() {
        
        navTitle = section?.name
    }
    
    override func setupTableView() {
        
        tableViewPlain.rowHeight = 80
        
        tableViewPlain.contentInset = UIEdgeInsetsMake(JKNavBarHeight, 0, JKCurrentHomeIndicatorHeight, 0)
        
        if #available(iOS 11.0, *) {
            
        } else {
            
            tableViewPlain.scrollIndicatorInsets = tableViewPlain.contentInset
        }
        
        tableViewPlain.register(UINib(nibName: "JKNewsListCell", bundle: nil), forCellReuseIdentifier: "JKNewsListCell")
        
        tableViewPlain.addFooterWithRefreshingTarget(target: self, refreshingAction: #selector(loadMoreData))
    }
    
    // MARK: - 加载数据
    
    override func loadNewData() {
        
        if section == nil {
            return
        }
        
        if section!.id == nil {
            return
        }
        
        JKNetworkingTool.shared.request(url: "http://news-at.zhihu.com/api/3/section/" + section!.id!, method: .get, parameters: nil) { (responseJson, error) in
            
            if error != nil {
                
                if self.stories.count > 0 { return }
                
                self.showReloadView()
                
                return
            }
            
            guard let json = responseJson as? [String : AnyObject] else {
                
                if self.stories.count > 0 { return }
                
                self.showReloadView()
                
                return
            }
            
            guard let stories = (json["stories"]) as? [[String : AnyObject]] else {
                
                if self.stories.count > 0 { return }
                
                self.showReloadView()
                
                return
            }
            
            guard let newsListModels = [JKNewsListModel].deserialize(from: stories) else {
                
                if self.stories.count > 0 { return }
                
                self.showReloadView()
                
                return
            }
            
            self.hideReloadView()
            
            self.stories = newsListModels as! [JKNewsListModel]
            
            if self.stories.count <= 0 { return }
            
            // 执行缓存
            JKSQLiteManager.cacheStoryLists(stories: stories, date: nil, isTop: false, isLatest: false, isMore: false)
            
            self.tableViewPlain.reloadData()
            
            guard let timestamp = (json["timestamp"]) as? NSNumber else {
                
                return
            }
            
            self.timestamps.removeAll()
            
            self.timestamps.append(timestamp)
            
            self.tableViewPlain.mj_footer.isHidden = false
        }
    }
    
    override func loadMoreData() {
        
        if self.timestamps.last == nil {
            return
        }
        
        JKNetworkingTool.shared.request(url: "http://news-at.zhihu.com/api/3/section/"  + section!.id! + "/before/" + "\(self.timestamps.last!)", method: .get, parameters: nil) { (responseJson, error) in
            
            self.tableViewPlain.mj_footer.endRefreshing()
            
            if error != nil {
                
                return
            }
            
            guard let json = responseJson as? [String : AnyObject] else {
                
                if self.stories.count > 0 { return }
                
                self.showReloadView()
                
                return
            }
            
            guard let stories = (json["stories"]) as? [[String : AnyObject]] else {
                
                
                return
            }
            
            guard let timestamp = (json["timestamp"]) as? NSNumber else {
                
                self.tableViewPlain.mj_footer.endRefreshingWithNoMoreData()
                
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.tableViewPlain.mj_footer.alpha = 0
                    
                }, completion: { (_) in
                    
                    self.tableViewPlain.mj_footer.isHidden = true
                })
                
                return
            }
            
            guard let newsListModels = [JKNewsListModel].deserialize(from: stories) else {
                
                if self.stories.count > 0 { return }
                
                self.showReloadView()
                
                return
            }
            
            self.timestamps.append(timestamp)
            
            self.stories += (newsListModels as! [JKNewsListModel])
            
            // 执行缓存
            JKSQLiteManager.cacheStoryLists(stories: stories, date: nil, isTop: false, isLatest: false, isMore: false)
            
            self.tableViewPlain.reloadData()
        }
    }
    
    // MARK: - 点击事件
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}

extension JKSectionStoryListViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.stories.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "JKNewsListCell") as? JKNewsListCell
        
        if cell == nil {
            
            cell = JKNewsListCell(style: UITableViewCellStyle.default, reuseIdentifier: "JKNewsListCell")
        }
        
        let model = self.stories[indexPath.row]
        
        model.alreadyRead = JKSQLiteManager.queryIsReadWithStoryID(storyID: model.id!)
        
        cell!.model = model
        
        return cell!
    }
}

extension JKSectionStoryListViewController {
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        super.tableView(tableView, didSelectRowAt: indexPath)
        
        let detailVc = JKNewsDetailViewController()
        
        detailVc.storyID = self.stories[indexPath.row].id
        detailVc.themeStories = self.stories
        detailVc.indexPath = indexPath
        detailVc.storyListVc = self
        
        navigationController?.pushViewController(detailVc, animated: true)
    }
}

extension JKSectionStoryListViewController: JKStoryListReadProtocol {
    
    func reloadReadStoryWith(indexPath: IndexPath?) {
        
        guard let _ = indexPath else { return }
        
        tableViewPlain.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.none)
    }
}
